package com.material.common.interceptor;

import com.material.common.annotation.PassToken;
import com.material.common.constant.Constants;
import com.material.common.core.domain.entity.SysUser;
import com.material.common.exception.LoginExpiredException;
import com.material.common.exception.ServiceException;
import com.material.common.utils.JwtUtil;
import com.material.common.utils.StringUtils;
import com.material.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * @author ganxinge
 */
public class AuthenticationInterceptor implements HandlerInterceptor
{
    //public static final String USER_KEY = "loginName";

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object object) throws Exception
    {
        // 从 http 请求头中取出
        String token = request.getHeader("token");
        // token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod))
        {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        // 检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class))
        {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required())
            {
                return true;
            }
        }
        // 执行认证
        if (StringUtils.isBlank(token))
        {
            //throw new ServiceException("token不能为空");
            throw new LoginExpiredException("token不能为空");
        }
        String username = JwtUtil.getUsername(token);
        if (username == null)
        {
            throw new LoginExpiredException("token invalid");
        }
        SysUser sysUser = sysUserService.selectUserByUserName(username);
        if (sysUser == null)
        {
            throw new LoginExpiredException("用户不存在，请重新登录");
        }
        // 验证 token
        if (!JwtUtil.verify(token, sysUser.getUserName(), sysUser.getPassword()))
        {
            throw new LoginExpiredException("非法token,或者登录超时");
        }
        // 设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(Constants.APP_USER_KEY, sysUser.getUserName());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
                           ModelAndView modelAndView) throws Exception
    {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception
    {
    }
}
